package com.smart.platform.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.platform.common.CustomException;
import com.smart.platform.common.Result;
import com.smart.platform.entity.Score;
import com.smart.platform.entity.Students;
import com.smart.platform.entity.TeaClasses;
import com.smart.platform.entity.Teachers;
import com.smart.platform.service.ScoreService;
import com.smart.platform.service.StudentsService;
import com.smart.platform.service.TeaClassesService;
import com.smart.platform.service.TeachersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

//教师信息功能模块（登录，退出，注册功能）
@Slf4j
@RestController
@RequestMapping("/Teachers")
@Api(tags = "教师数据接口")
public class TeachersController {

    @Autowired
    private TeachersService teachersService;

    @Autowired
    private ScoreService scoreservice;

    @Autowired
    private TeaClassesService teaClassesService;

    @Autowired
    private StudentsService studentsService;

    /**
     * 教师登录
     *
     * @param request
     * @param teachers
     * @return
     */
    @ApiOperation(value = "教师登录接口", notes = "需要教师的工号userId和密码：password")
    @PostMapping("/login")
    public Result<Teachers> login(HttpServletRequest request, @RequestBody Teachers teachers) {
        //1.将传递过来的密码先进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(teachers.getPassword().getBytes());

        //2.根据页面提交的学生学号来查询数据库
        LambdaQueryWrapper<Teachers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachers::getUserId, teachers.getUserId());
        Teachers teacher = teachersService.getOne(queryWrapper);

        //3.如果没有查询到则返回登录失败结果
        if (teacher == null) {
            throw new CustomException("账号输入错误");
        }

        //4.密码比对，如果不一致则返回登录失败的结果（注意这里的逻辑，是一致放行，不一致运行，所以前面的非号一定要注意！！！！！）
        if (!teacher.getPassword().equals(password)) {
            throw new CustomException("密码输入错误");
        }

        //5.登录成功，将员工id存入session并返回登录成功的结果

        request.getSession().setAttribute("userId", teacher.getUserId());
        log.info("登录的session:{}", request.getSession().getAttribute("userId"));
        return Result.success(teacher);
    }

    /**
     * 教师后台退出方法
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "教师退出接口", notes = "不需要任何请求参数直接请求该路径即可")
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        //从当前的session中移除userId
        request.getSession().removeAttribute("userId");
        return Result.success("退出成功");
    }

    /**
     * 教师注册方法
     *
     * @param teachers
     * @return
     */
    @ApiOperation(value = "教师注册接口", notes = "注册只需要教师的工号：userId 和 姓名：name")
    @PostMapping("/save")
    public Result<String> save(@RequestBody Teachers teachers) {
        log.info("新增员工，员工信息：{}", teachers.toString());

        //初始密码默认为123456 后续可以进行修改
        teachers.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        teachersService.save(teachers);

        return Result.success("教师注册成功");
    }

    /**
     * 修改操作 教师信息修改包括 密码 和 学校
     *
     * @param
     * @return
     */
    @ApiOperation(value = "教师信息修改接口", notes = "在已登录的条件下点击信息修改功能后前端需要以json格式传递对应字段的信息数据")
    @PutMapping("/update")
    public Result<String> update(HttpServletRequest request, @RequestBody Teachers teachers) {
        log.info(teachers.toString());

        //通过session 获取当前登录教师的userId
        String userId = (String) request.getSession().getAttribute("userId");

        //将前端传过来的密码先进行一下md5加密
        String password = DigestUtils.md5DigestAsHex(teachers.getPassword().getBytes());

        //将前端传过来的密码更新一下
        teachers.setPassword(password);

        //通过添加添加构造器 针对userId进行修改
        LambdaQueryWrapper<Teachers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachers::getUserId, userId);

        teachersService.update(teachers, queryWrapper);

        return Result.success("教师信息修改成功");
    }


    /**
     * 登录以后通过当前登录用户的session来获取到 userId 用于后续数据查询
     * 测试的时候先直接给定数据
     *
     * @param request
     * @param
     * @return
     */
    @ApiOperation(value = "教师信息查询接口", notes = "通过获取当前session中的user进行定位 因此只需要请求这个接口即可")
    @GetMapping("/infoSearch")
    public Result<Teachers> infoSearch(HttpServletRequest request) {
        // 获取用户ID
        String userId = (String) request.getSession().getAttribute("userId");

        // 创建查询条件构造器
        LambdaQueryWrapper<Teachers> queryWrapper = new LambdaQueryWrapper<>();

        // 设置查询条件
        queryWrapper.eq(Teachers::getUserId, userId);
        // 获取教师信息
        Teachers teacher = teachersService.getOne(queryWrapper);

        // 返回结果
        return Result.success(teacher);
    }


    /**
     * 条件分页查询学生信息
     *
     * @param request
     * @param studentClasses
     * @param name
     * @param studentUserId
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/StudentsPage")
    @ApiOperation(value = "教师查看学生信息接口", notes = "根据教师的工号进行查询 其中又支持对班级 姓名 学号进行查询 默认展示所有学生")
    public Result<Page> StudentPage(HttpServletRequest request, Integer studentClasses, String name, String studentUserId, Integer page, Integer pageSize) {
        log.info("page = {} , pageSize = {}", page, pageSize);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //获取当前教师的userId
        String userId = (String) request.getSession().getAttribute("userId");

        LambdaQueryWrapper<TeaClasses> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeaClasses::getUserId, userId);
        //根据教师工号获取到他所管理的年级和班级数据
        List<TeaClasses> list = teaClassesService.list(queryWrapper);

        //如果是默认情况下 就展示所有学生的信息
        List<Integer> listClasses = new ArrayList<>();
        int grade = list.get(0).getGrade();

        //通过for循环的方式将教师所管理的班级放入到集合当中
        for (TeaClasses teaClasses : list) {
            listClasses.add(teaClasses.getClasses());
        }


        LambdaQueryWrapper<Students> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //in的添加条件是后面需要要一个list类型的集合
        //首先根据班级查询 然后是对姓名进行模糊查询 再是对学号进行精确查询
        //如果三者均为空就按照教师所管理的所有学生进行查询
        lambdaQueryWrapper
                .eq(Students::getGrade, grade)
                .in(Students::getClasses, listClasses)
                .eq(studentClasses != null, Students::getClasses, studentClasses)
                .like(StringUtils.isNotEmpty(name), Students::getName, name)
                .eq(StringUtils.isNotEmpty(studentUserId), Students::getUserId, studentUserId)
                .orderByAsc(Students::getClasses);

        studentsService.page(pageInfo, lambdaQueryWrapper);

        return Result.success(pageInfo);

    }


    /**
     * 条件分页查询学生成绩
     *
     * @param request
     * @param page
     * @param pageSize
     * @param course
     * @param studentClasses
     * @param studentUserId
     * @param state
     * @return
     */
    @ApiOperation(value = "分页展示某次考试中某个班级所有学生的考试成绩")
    @GetMapping("/ScorePage")
    public Result<Page> ScorePage(HttpServletRequest request, Integer page, Integer pageSize, Integer course, Integer studentClasses, String studentUserId, Integer state) {
        log.info("page = {} , pageSize = {}", page, pageSize);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //获取当前教师的userId
        String userId = (String) request.getSession().getAttribute("userId");

        LambdaQueryWrapper<TeaClasses> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeaClasses::getUserId, userId);
        //根据教师工号获取到他所管理的年级和班级数据
        List<TeaClasses> list = teaClassesService.list(queryWrapper);

        //如果是默认情况下 就展示所有学生的信息

        List<Integer> listClasses = new ArrayList<>();
        int grade = list.get(0).getGrade();

        //通过for循环的方式将教师所管理的班级放入到集合当中
        for (TeaClasses teaClasses : list) {
            listClasses.add(teaClasses.getClasses());
        }


        //构造条件构造器
        LambdaQueryWrapper<Score> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        lambdaQueryWrapper
                .eq(Score::getGrade, grade)
                .in(Score::getClasses, listClasses)
                .eq(Score::getState, state)
                .eq(studentClasses != null, Score::getClasses, studentClasses)
                .eq(StringUtils.isNotEmpty(studentUserId), Score::getUserId, studentUserId);


        //添加排序条件
        //根据最后的更新时间进行降序排序 Desc：降序 Asc：升序
        //选择科目进行降序排序 默认情况下对总分进行排序
        if (course == null) {
            course = 10;
        }
        switch (course) {
            case 1:
                lambdaQueryWrapper.orderByDesc(Score::getChinese);
                break;
            case 2:
                lambdaQueryWrapper.orderByDesc(Score::getMath);
                break;
            case 3:
                lambdaQueryWrapper.orderByDesc(Score::getEnglish);
                break;
            case 4:
                lambdaQueryWrapper.orderByDesc(Score::getPhysics);
                break;
            case 5:
                lambdaQueryWrapper.orderByDesc(Score::getChemistry);
                break;
            case 6:
                lambdaQueryWrapper.orderByDesc(Score::getBiology);
                break;
            case 7:
                lambdaQueryWrapper.orderByDesc(Score::getPolitical);
                break;
            case 8:
                lambdaQueryWrapper.orderByDesc(Score::getHistory);
                break;
            case 9:
                lambdaQueryWrapper.orderByDesc(Score::getGeography);
                break;
            default:
                lambdaQueryWrapper.orderByDesc(Score::getTotal).orderByAsc(Score::getUserId);
        }

        //执行查询
        scoreservice.page(pageInfo, lambdaQueryWrapper);

        return Result.success(pageInfo);
    }


}
